/**
 * Class:				WordsManager.java
 * 
 * Project:				Bio-inspired car commander
 * 
 * Subproject:			Word Detector
 * 
 * Date: 				Mai - Juillet 2011
 * 
 * Auteurs:				Bruno Da Silva
 * 						Thomas Jordan
 * 
 * Description:
 * 
 * Structure de gestion de la liste des mots qui permet de faire le matching entre
 * le mot, et sa position dans la liste qui est utilisée pour numérter les
 * sorties du réseau de neurones et ainsi retranscrire un "pattern" d'activation en
 * un mot de la liste.
 * 
 */
package ch.sda.bioinspiredcarcommander.words;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import android.content.Context;
import android.content.SharedPreferences;

public class WordsManager {
	
	private static final String PREFS_NAME = "wordsList";
	private static WordsManager SharedManager = null;
	private Context ctx = null;
	
	
	private ArrayList<String> words = new ArrayList<String>();
	
	public static WordsManager sharedManager(Context ctx) {
		if (SharedManager == null) {
			SharedManager = new WordsManager(ctx);
		}
		return SharedManager;
	}
	
	private WordsManager(Context ctx) {
		this.ctx = ctx;
		loadWords();
	}
	
	@SuppressWarnings("unchecked")
	private void loadWords() {
		// Restore preferences
		SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);
		
		Map<String, String> entries = (Map<String, String>) settings.getAll();
		
		for (Entry<String, String> e : entries.entrySet()) {
			words.add(0,e.getValue());
//			words.add(Integer.parseInt(e.getKey()), e.getValue());
		}
	}
	
	@SuppressWarnings("unchecked")
	private void saveWords() {
		SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		
		Map<String, String> entries = (Map<String, String>) settings.getAll();
		
		for (Entry<String, String> e : entries.entrySet()) {
			editor.remove(e.getKey());
		}
		
		for (int i=0; i<words.size(); i++) {
			editor.putString(i+"", words.get(i));
		}
		
		editor.commit();
	}

	public void addWord(String w) {
		if (!words.contains(w)) {
			words.add(w);
		}
	}
	
	public void removeWord(String w) {
		words.remove(w);
	}
	
	@SuppressWarnings("unchecked")
	public List<String> getWords() {
		return (List<String>) words.clone();
	}
	
	public void save() {
		saveWords();
	}
	
	public void reset() {
		words.removeAll(words);
		saveWords();
	}
	
}
